package com.news.gpb.controller;


import com.news.gpb.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

@CrossOrigin("http://localhost:8080")
@RestController
public class UploadController {

    @Autowired
    UserDao userDao;

    @RequestMapping("/upload/{user_id}")
    String upPic(@PathVariable("user_id") int user_id,@RequestParam("pic") MultipartFile pic) throws IOException {
        /*
         * 编码为字符串*/
        String s = Base64Utils.encodeToString(pic.getBytes());

        /* *
         *2.解码成字节数组
         */
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(s);

        /*
         * 3.字节流转文件
         */
        File fileMkdir = new File( "D:\\DeskTop\\graduation-project\\gp-f\\src\\assets\\avatar\\");
        if (!fileMkdir.exists()) {
            fileMkdir.mkdir();
        }
        String pathName = fileMkdir.getPath() + "\\" + user_id+".jpg";
        userDao.uploadPic(pathName,user_id);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pathName);
            fos.write(bytes);
        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return pathName;
    }
}
